﻿using UnityEngine;

public class Game
{
    public Board m_Board;
    public Player m_CurrentPlayer;
    public Player m_Winner;
    public bool m_GameOver;

    public int ActionCount => m_Board.m_EmptyCells.Count;

    public Game()
    {
        m_Board = new Board();
    }
    public void Start()
    {
        m_Board.Start();
        m_CurrentPlayer = Player.Blue;
        m_GameOver = false;
    }
    public static Game CopyFrom(Game other)
    {
        // deep copy
        Game copyGame = ObjectPool<Game>.Claim();
        copyGame.m_Board = Board.CopyFrom(other.m_Board);
        copyGame.m_CurrentPlayer = other.m_CurrentPlayer;
        copyGame.m_Winner = other.m_Winner;
        copyGame.m_GameOver = other.m_GameOver;
        return copyGame;
    }
    public void Release()
    {
        m_Board.Release();
        m_Board = null;
        ObjectPool<Game>.Release(this);
    }
    public void Step(Vector2Int pos)
    {
        if (m_Board[pos].m_BelongTo != Player.None) return;
        if (m_Board.TakeStep(m_CurrentPlayer, pos, out Player winner))
        {
            // win
            m_GameOver = true;
            m_Winner = winner;
        }
        else
        {
            m_CurrentPlayer = m_CurrentPlayer == Player.Blue ? Player.Red : Player.Blue;
        }
    }

    public Vector2Int RandomEmptyPos
    {
        get
        {
            int actionId = Random.Range(0, ActionCount);
            return m_Board.m_EmptyCells[actionId];
        }
    }

    /// <summary>
    /// ramdom run to end, return the winner
    /// </summary>
    /// <returns></returns>
    public Player Rollout()
    {
        while (!m_GameOver)
        {
            Step(RandomEmptyPos);
        }
        return m_Winner;
    }
}